package com.servlet;

import com.bean.Book;
import com.dao.BooksUtilsDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;


@WebServlet("/CountServlet")
public class CountServlet extends HttpServlet {
  
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        BooksUtilsDao dao = new BooksUtilsDao();
        String button = request.getParameter("button");
        String cartid = request.getParameter("cartid");
        String amount = request.getParameter("amount");
        try {
            if (button.equals("+")) {
                dao.add(cartid);
                dao.totalprice(cartid);
            } else {
                int intamount = Integer.parseInt(amount);
                if (intamount <= 1) {
                    response.sendRedirect("CountServlet");
                    return;
                }
                dao.reduce(cartid);
                dao.totalprice(cartid);
            }
            @SuppressWarnings("unchecked")
			ArrayList<Book> cart = (ArrayList<Book>) session.getAttribute("cart");
            ArrayList<Book> cart1 = new ArrayList<Book>();
            for (Book book : cart) {
                String id = book.getId();
                ArrayList<Book> bookid = (ArrayList<Book>) dao.findId(id);
                cart1.add(bookid.get(0));
            }
            session.removeAttribute("cart");
            session.setAttribute("cart", cart1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.sendRedirect("CartServlet");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
